package com.reger.web.interceptor;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.LoggerFactory;

import com.reger.core.Context;
import com.reger.web.config.WebProperties;

public class RequestFilter {
	private static final org.slf4j.Logger logger = LoggerFactory.getLogger(RequestFilter.class);
	public static final List<String> methods = Arrays.asList("GET", "POST", "PUT", "DELETE");

	private WebProperties webProperties;

	public RequestFilter(WebProperties webProperties) {
		this.webProperties = webProperties;
	}

	/**
	 * 过滤免校验的请求方法
	 * 
	 * @return
	 */
	public boolean filterRequestMethod() {
		HttpServletRequest req = Context.getRequest();
		if (req == null || !methods.contains(req.getMethod().toUpperCase())) {
			return true;
		}
		return false;
	}

	/**
	 * 过滤免校验的url
	 * 
	 * @return
	 */
	public boolean filterUrl() {
		String apiUrl = Context.getRequestUri();
		List<String> allowedApiPath = webProperties.getAllowedApiPath();// 获取排除列表
		List<String> exposedApiPath = webProperties.getExposedApiPath();// 获取排除列表
		if (exposedApiPath != null) {
			for (int i = 0; i < exposedApiPath.size(); i++) {
				String apiPath = exposedApiPath.get(i);
				if (apiUrl.endsWith(apiPath) || simpleMatch(apiPath, apiUrl)) {
					logger.debug("请求({})在匹配({})时确定为校验访问", apiPath, apiUrl);
					return false;
				}
			}
		}
		if (allowedApiPath != null) {
			for (int i = 0; i < allowedApiPath.size(); i++) {
				String apiPath = allowedApiPath.get(i);
				if (apiUrl.endsWith(apiPath) || simpleMatch(apiPath, apiUrl)) {
					logger.debug("请求({})在匹配({})时确定为允许访问", apiPath, apiUrl);
					return true;
				}
			}
		}
		return false;
	}

	private static boolean simpleMatch(String apiPath, String apiUrl) {
		return Pattern.matches(apiPath, apiUrl);
	}
}
